<script setup>
defineProps({
  options: Array,
  block: Boolean,
})

const emit = defineEmits(['change'])

const value = defineModel()

const segmentRailRef = ref(null)
const segmentCapsuleElRef = ref(null)

watch(value, () => {
  updateSegmentPosition()
})

onMounted(() => {
  updateSegmentPosition()
})

function handleChange(item) {
  value.value = item.value
  emit('change', item)
}

function getCurrentEl() {
  return segmentRailRef.value?.querySelector(`[data-name=${value.value}]`)
}

function updateSegmentPosition() {
  const activeTabEl = getCurrentEl()

  if (activeTabEl && segmentCapsuleElRef.value) {
    const { offsetWidth, offsetHeight, offsetLeft } = activeTabEl

    segmentCapsuleElRef.value.style.width = `${offsetWidth}px`
    segmentCapsuleElRef.value.style.height = `${offsetHeight}px`
    segmentCapsuleElRef.value.style.transform = `translateX(${offsetLeft - 3}px)`

    segmentRailRef.value.style.clipPath = `rect(0 ${offsetWidth + offsetLeft + 3}px 100% ${offsetLeft - 3}px round 3px)`
  }
}
</script>

<template>
  <div :class="[block && 'is-block']" class="shine-segment">
    <div ref="segmentRailRef" class="shine-segment-rail shine-segment-rail--top-level">
      <div ref="segmentCapsuleElRef" class="shine-segment-capsule" />
      <div
        v-for="(item, i) of options" :key="i" :data-name="item.value" class="shine-segment-item"
        @click="handleChange(item)"
      >
        <span class="shine-segment__label">{{ item.label }}</span>
      </div>
    </div>

    <div class="shine-segment-rail">
      <div
        v-for="(item, i) of options" :key="i" class="shine-segment-item" @click="handleChange(item)"
      >
        <span class="shine-segment__label">{{ item.label }}</span>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.shine-segment {
  @apply relative inline-flex bg-#f7f7fa;
  font-size: 12px;
  border-radius: 3px;
  min-height: 32px;

  &.is-block {
    @apply flex;
  }

  &-rail {
    @apply flex relative w-full min-h-full transition-all-300;
    padding: 3px;

    &--top-level {
      @apply absolute z-2;

      .shine-segment-item {
        @apply c-#1f2225;
      }
    }
  }

  &-capsule {
    @apply absolute bg-#FFFFFF pointer-events-none transition-all-300;
    border-radius: 3px;
    box-shadow: 0 0 3px 0 rgba(0, 0, 0, .08);
  }

  &-item {
    @apply flex flex-1 items-center justify-center cursor-pointer c-#CFD3DC;
    padding: 0 10px;
  }

  &__label {
    @apply text-truncate z-1;
  }
}
</style>
